<template>
	<page-wrap>
		<div class="flex flex-col overflow-auto md:bg-cover md:bg-center md:bg-no-repeat">
			<div class="view-account-header"></div>
			<div class="mx-auto min-w-[320px] max-w-[384px] flex-1 px-3 py-8">
				<div class="py-8 text-center">
					<div class="view-account-top-logo">
						<!-- <img :src="websiteConfig.loginImage" alt="" /> -->
					</div>
					<h2 class="mb-2 text-2xl font-semibold">{{ isLogin ? '欢迎回来' : '创建新账号' }}</h2>
				</div>
				<div class="view-account-form">
					<n-form ref="formRef" label-placement="left" size="large" :model="formData" :rules="rules">
						<n-form-item path="username">
							<n-input v-model:value="formData.username" :placeholder="isLogin ? '请输入用户名' : '设置用户名'">
								<template #prefix>
									<n-icon size="18" color="#808695">
										<PersonOutline />
									</n-icon>
								</template>
							</n-input>
						</n-form-item>
						<n-form-item path="password">
							<n-input v-model:value="formData.password" type="password" showPasswordOn="click" :placeholder="isLogin ? '请输入密码' : '设置密码'">
								<template #prefix>
									<n-icon size="18" color="#808695">
										<LockClosedOutline />
									</n-icon>
								</template>
							</n-input>
						</n-form-item>
						<template v-if="isLogin">
							<n-form-item path="captcha" v-if="needCaptcha">
								<div class="flex gap-2">
									<n-input v-model:value="formData.captcha" placeholder="请输入图形验证码">
										<template #prefix>
											<n-icon size="18" color="#808695">
												<ShieldCheckmarkOutline />
											</n-icon>
										</template>
									</n-input>
									<div class="flex w-[150px] items-center gap-2">
										<img v-if="captchaBase64" :src="captchaBase64" alt="验证码" class="cursor-pointer rounded" @click="refreshCaptcha" />
									</div>
								</div>
							</n-form-item>
						</template>
						<template v-if="!isLogin">
							<n-form-item path="confirmPassword">
								<n-input v-model:value="formData.confirmPassword" type="password" showPasswordOn="click" placeholder="确认密码">
									<template #prefix>
										<n-icon size="18" color="#808695">
											<LockClosedOutline />
										</n-icon>
									</template>
								</n-input>
							</n-form-item>
							<n-form-item path="nickname">
								<n-input v-model:value="formData.nickname" placeholder="设置昵称">
									<template #prefix>
										<n-icon size="18" color="#808695">
											<PersonCircleOutline />
										</n-icon>
									</template>
								</n-input>
							</n-form-item>
						</template>
						<n-form-item>
							<n-button :disabled="loading" type="primary" @click="handleSubmit" size="large" :loading="loading" block @keyup.enter="handleSubmit">
								{{ isLogin ? '登录' : '注册' }}
							</n-button>
						</n-form-item>
						<n-form-item class="text-[#515a6e]" v-if="!existAdmin">
							<div class="flex w-full items-center" v-if="isLogin">
								<div class="ml-auto flex-initial">
									<n-button text type="primary" @click="toggleAuthMode">注册管理员账号</n-button>
								</div>
							</div>
							<div class="flex justify-center" v-else>
								<span class="text-gray-600">已有账号？</span>
								<n-button text type="primary" @click="toggleAuthMode">返回登录</n-button>
							</div>
						</n-form-item>
					</n-form>
				</div>
			</div>
		</div>
	</page-wrap>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { useAuthStoreHook } from '@/store/auth';
import { useMenuStoreHook } from '@/store/menu';
import { LockClosedOutline, PersonCircleOutline, PersonOutline, ShieldCheckmarkOutline } from '@vicons/ionicons5';

interface FormState {
	username: string;
	password: string;
	confirmPassword?: string;
	nickname?: string;
	captcha?: string;
}

const { message } = useFeedback(['message']);
const formRef = ref();
const loading = ref(false);
const isLogin = ref(true);
const captchaBase64 = ref<string>('');

const needCaptcha = ref(false);

const uniIdRedirectUrl = ref<string>('');

const existAdmin = ref(true);

const { loginSuccess } = useAuthStoreHook();
const { getMenuList } = useMenuStoreHook();
const uniIdCo = uniCloud.importObject('uni-id-co', {
	customUI: true,
});

const formData = ref<FormState>({
	username: '',
	password: '',
	confirmPassword: '',
	nickname: '',
	captcha: '',
});

const rules = {
	username: { required: true, message: '请输入用户名', trigger: 'blur' },
	password: { required: true, message: '请输入密码', trigger: 'blur' },
	confirmPassword: {
		required: true,
		message: '请确认密码',
		trigger: 'blur',
		validator: (rule: any, value: string) => {
			return !isLogin.value ? value === formData.value.password : true;
		},
	},
	nickname: {
		required: true,
		message: '请输入昵称',
		trigger: 'blur',
		validator: (rule: any, value: string) => {
			if (!isLogin.value) {
				if (!value || value.length < 2 || value.length > 20) {
					return new Error('昵称长度需要在2-20个字符之间');
				}
			}
			return true;
		},
	},
	captcha: {
		required: true,
		message: '请输入验证码',
		trigger: 'blur',
		validator: (rule: any, value: string) => {
			if (isLogin.value && (!value || value.length !== 4)) {
				return new Error('请输入4位验证码');
			}
			return true;
		},
	},
};

const getCaptcha = async () => {
	try {
		const res = await uniIdCo.createCaptcha({
			scene: 'login-by-pwd',
		});
		captchaBase64.value = res.captchaBase64;
	} catch (error: any) {
		message.error(error.message || '获取验证码失败');
	}
};

const refreshCaptcha = async () => {
	try {
		const res = await uniIdCo.refreshCaptcha();
		captchaBase64.value = res.captchaBase64;
	} catch (error: any) {
		message.error(error.message || '刷新验证码失败');
	}
};

const toggleAuthMode = () => {
	isLogin.value = !isLogin.value;
	formData.value = {
		username: '',
		password: '',
		confirmPassword: '',
		nickname: '',
		captcha: '',
	};
	if (isLogin.value) {
		getCaptcha();
	} else {
		captchaBase64.value = '';
	}
};

const handleSubmit = (e: any) => {
	e.preventDefault();
	formRef.value.validate(async (errors: any) => {
		if (!errors) {
			const { username, password, nickname, captcha } = formData.value;

			loading.value = true;

			try {
				if (isLogin.value) {
					// 登录逻辑
					const params: FormState = {
						username,
						password,
						captcha,
					};
					await uniIdCo.login(params);
					await getMenuList();
					loginSuccess();
					uni.navigateTo({
						url: uniIdRedirectUrl.value || '/pages/index/index',
					});
				} else {
					// 注册逻辑
					const params: FormState = {
						username,
						password,
						nickname,
					};
					const res = await uniIdCo.registerAdmin(params);
				}
				message.destroyAll();
				message.success(isLogin.value ? '登录成功' : '注册成功');
			} catch (error: any) {
				message.error(error.message || '操作失败');
				if (error.errCode == 'uni-id-captcha-required') {
					needCaptcha.value = true;
					getCaptcha();
				} else if (needCaptcha.value) {
					//登录失败，自动重新获取验证码
					getCaptcha();
				}
			} finally {
				loading.value = false;
			}
		} else {
			message.error(isLogin.value ? '请填写完整登录信息' : '请填写完整注册信息');
		}
	});
};

onLoad((e) => {
	if (e?.uniIdRedirectUrl) {
		uniIdRedirectUrl.value = decodeURIComponent(e.uniIdRedirectUrl);
	}

	const existAdminCache = uni.getStorageSync('existAdmin');
	if (existAdminCache) {
		existAdmin.value = existAdminCache;
	} else {
		api.user.existAdmin().then((res) => {
			uni.setStorageSync('existAdmin', res);
			existAdmin.value = res;
		});
	}
});
</script>
